import Papa from "papaparse"; // 解析cvs插件 市面上使用较多的
import jschardet from "jschardet"; // 编码识别
import { UploadOutlined } from "@ant-design/icons";
import { Button, message } from "antd";
import { useRef, useState } from "react";
import "./index.less";

export default ({
  value,
  onChange,
  showUploadList = false,
  loading = false,
  type = "yl", // yl  LH SC
}) => {
  const fileRef = useRef(null);
  const [fileNames, setFileNames] = useState([]);

  //这种方式得到的是一种二进制串
  const checkEncoding = (base64Str) => {
    const str = window.atob(base64Str.split(";base64,")[1]); // 用于解码使用 base-64 编码的字符
    let encodingMap = jschardet.detect(str);
    let encoding = "";
    encoding = encodingMap.encoding;
    // 有时候会识别错误
    if (encoding === "windows-1252") {
      encoding = "ANSI";
    }
    return encoding;
  };

  const beforeUpload = () => {
    let files = fileRef.current.files;
    const fileNames = Array.from(files).map((item) => item.name);
    setFileNames(fileNames);

    if (files.length === 0) return;
    const file = files[0];
    console.log("file===", file);
    const fileNameType = file.name.split("-")?.[1];
    if (fileNameType !== type) {
      message.error(`请上传正确类型的文件`);
      return;
    }
    const postDataArr = [];
    const fReader = new FileReader();
    //  readAsDataURL 读取本地文件 得到的是一个base64值
    fReader.readAsDataURL(file);
    // 读取文件成功
    fReader.onload = (evt) => {
      const data = evt.target?.result;
      if (typeof data === "string") {
        const encoding = checkEncoding(data);
        //papaparse.js 用来解析转换成二维数组
        Papa.parse(file, {
          encoding: encoding,
          complete: async (results) => {
            // UTF8 \r\n与\n混用时有可能会出问题
            const res = results.data;
            //去除最后的空行 有些解析数据尾部会多出空格
            if (res[res.length - 1] === "") {
              res.pop();
            }
            console.log("res===", res);
            const list = res.slice(1);
            list.forEach((item) => {
              postDataArr.push({
                label: item[1],
                area: item[2],
                circ: item[3],
                feret: item[4],
                feretX: item[5],
                feretY: item[6],
                feretAngle: item[7],
                minFeret: item[8],
                ar: item[9],
                round: item[10],
                solidity: item[11],
              });
            });
            onChange(postDataArr);
          },
        });
      }
    };
  };

  return (
    <div className="upload-container">
      <Button className="my-upload-btn" loading={loading} type="text">
        上传文件
      </Button>
      {loading ? null : (
        <input
          className="add-input"
          type="file"
          ref={fileRef}
          multiple={true}
          onChange={beforeUpload}
        />
      )}

      {showUploadList && fileNames.length ? (
        <ul>
          {fileNames.map((item) => (
            <li key={item}>{item}</li>
          ))}
        </ul>
      ) : null}
    </div>
  );
};
